package com.white.algebra.utils;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class SensitiveWordInit {
    // 字符编码
    private String ENCODING = "UTF-8";
    // 初始化敏感字库
    public Map initKeyWord() {
    // 读取敏感词库 ,存入Set中
        Set<String> wordSet = readSensitiveWordFile();
        return addSensitiveWordToHashMap(wordSet);
    }

    // 读取敏感词库 ,存入HashMap中
    private Set<String> readSensitiveWordFile() {
        Set<String> wordSet = null;
        InputStream inputStream = SensitiveWordInit.class.getClassLoader().getResourceAsStream("CensorWords.txt");
        try {
            // 读取文件输入流
            //InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING);
            InputStreamReader read = new InputStreamReader(inputStream, ENCODING);
            wordSet = new HashSet<String>();
            BufferedReader br = new BufferedReader(read);
            String txt = null;
            while ((txt = br.readLine()) != null) {
                wordSet.add(txt);
            }
            br.close();

            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wordSet;
    }

    private Map addSensitiveWordToHashMap(Set<String> wordSet) {
        Map wordMap = new HashMap(wordSet.size());
        for (String word : wordSet) {
            Map nowMap = wordMap;
            for (int i = 0; i < word.length(); i++) {
                char keyChar = word.charAt(i);
                Object tempMap = nowMap.get(keyChar);
                if (tempMap != null) {
                    nowMap = (Map) tempMap;
                }

                else {
                    Map<String, String> newMap = new HashMap<String, String>();
                    newMap.put("isEnd", "0");
                    nowMap.put(keyChar, newMap);
                    nowMap = newMap;
                }
                if (i == word.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
            }
        }
        return wordMap;
    }
}
